import Vue from 'vue';
import Router from 'vue-router';
import Views from './views';
import appService from '@/utils/appService';
import config from '@/utils/config';
Vue.use(Router);

const vueRouter = new Router({
  /** history or hash */
  mode: 'history',
  base: config.publicPath,
  routes: [...Views]
});

vueRouter.beforeEach((to, from, next) => {
  // 如果设置了页面标题
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  if (to.meta.noAuthc) {
    next();
    return;
  }
  // 如果访问非登陆页面且用户没有登陆
  if (!appService.getUserInfo()) {
    if (to.path !== '/signin') {
      next('/signin');
      return;
    }
  }
  let permissionPass = true;
  let rolePass = true;
  if (to.meta.permission) {
    /** 权限检查 */
    permissionPass = appService.hasPermission(to.meta.permission);
  }
  if (to.meta.role) {
    /** 角色检查 */
    rolePass = appService.hasRole(to.meta.role);
  }
  if (permissionPass && rolePass) {
    next();
  } else {
    next('/403');
  }
});

window.vueRouter = vueRouter;

export default vueRouter;
